package dao

import (
	"go_my_framework/app/core/db"
	"go_my_framework/app/model"
	"time"
)

type AdminDao interface {
	FindRow(username string) model.Admin
	GetList(page int, limit int, username string) ([]model.Admin, int64, error)
	Create(username string, password string, roleId int, realName string, mobile string) error
	Update(id int, data model.Admin) error
	Del(id int) error
	GetAllAdmin() []model.Admin
}

func NewAdminDaoImpl() AdminDao {
	return new(AdminDaoImpl)
}

type AdminDaoImpl struct {

}

func (a *AdminDaoImpl) FindRow(username string) (data model.Admin) {
	db.Instance().
		Model(model.Admin{}).
		Where("username = ?", username).
		First(&data)
	return data
}

func (a *AdminDaoImpl) GetList(page int, limit int, username string) (data []model.Admin, count int64, err error) {
	obj := db.Instance().Model(model.Admin{})
	if username != "" {
		obj = obj.Where("username = ?", username)
	}
	obj = obj.Count(&count)
	err = obj.Limit(limit).Offset((page - 1) * limit).Find(&data).Error
	return
}

func (a *AdminDaoImpl) Create(username string, password string, roleId int, realName string, mobile string) error {
	dateTime := time.Now().Format("2006-01-02 15:04:05")
	data := model.Admin{
		Username:  username,
		Password:  password,
		RoleId:    roleId,
		RealName:  realName,
		Mobile:    mobile,
		Status:    1,
		LoginDt:   dateTime,
	}
	return db.Instance().Model(&model.Admin{}).Create(&data).Error
}

func (a *AdminDaoImpl) Update(id int, data model.Admin) error {
	return db.Instance().Model(model.Admin{}).Where("id = ?", id).Updates(data).Error
}

func (a *AdminDaoImpl) Del(id int) error {
	return db.Instance().Where("id = ?", id).Delete(model.Admin{}).Error
}

func (a *AdminDaoImpl) GetAllAdmin() []model.Admin {
	var data []model.Admin
	db.Instance().Model(model.Admin{}).Find(&data)
	return data
}